package com.qdsgjsfk.vision.base;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;

import java.lang.ref.WeakReference;

import butterknife.ButterKnife;

import com.qdsgjsfk.vision.R;
import com.qdsgjsfk.vision.ui.LoginActivity;

import util.NetworkUtil;

public abstract class BaseActivity extends AppCompatActivity {

    public PopupWindow popWinChoose;

    public ImageView btn_back;

    public boolean flag = false;
    protected Activity mContext;

    private long lastClickTime = 0L;
    private static final int FAST_CLICK_DELAY_TIME = 500;  // 快速点击间隔
    private static ProgressDialog progressDialog;

    /**
     * 里面的延时消息在得到处理前，会一直保存在主线程的消息队列里持续10分钟。而且，由上文可知，
     * 这条消息持有对handler的引用，而handler又持有对其外部类（在这里，即BaseActivity）的潜在引用。
     * 这条引用关系会一直保持直到消息得到处理，从而，这阻止了SBaseActivity被垃圾回收器回收，同时造成应用程序的泄漏。
     * 注意，上面代码中的Runnable类--非静态匿名类--同样持有对其外部类的引用。从而也导致泄漏。
     *
     * @time 2020/4/23 10:45
     */


    private static class MyHandler extends Handler {
        private final WeakReference<BaseActivity> mActivity;

        public MyHandler(BaseActivity activity) {
            mActivity = new WeakReference<BaseActivity>( activity );
        }

        @Override
        public void handleMessage(Message msg) {
            BaseActivity activity = mActivity.get();
            if (activity != null) {
                // ...
            }
        }
    }


    private final MyHandler mHandler = new MyHandler( this );

    /**
     * Instances of anonymous classes do not hold an implicit
     * reference to their outer class when they are "static".
     */
    private static final Runnable sRunnable = new Runnable() {
        @Override
        public void run() {
            progressDialog.dismiss();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            finish();
            return;
        }
        mContext = this;
        doBeforeSetcontentView();
        setContentView( getLayoutResource() );
        ButterKnife.bind( this );
        btn_back = findViewById( R.id.btn_back );
        if (btn_back != null) {
            btn_back.setOnClickListener( new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            } );
        }
        initData();
        initViews();
        initState();
    }


    /**
     * 设置layout前配置
     */
    private void doBeforeSetcontentView() {
        // 把actvity放到application栈中管理
//        AppManager.getAppManager().addActivity(this);
        // 无标题
        requestWindowFeature( Window.FEATURE_NO_TITLE );
        // 设置竖屏
        setRequestedOrientation( ActivityInfo.SCREEN_ORIENTATION_PORTRAIT );
    }

    /**
     * 通过Class跳转界面
     **/
    public void startActivity(Class<?> cls) {
        startActivity( cls, null );
    }

    /**
     * 通过Class跳转界面
     **/
    public void startActivityForResult(Class<?> cls, int requestCode) {
        startActivityForResult( cls, null, requestCode );
    }

    /**
     * 含有Bundle通过Class跳转界面
     **/
    public void startActivityForResult(Class<?> cls, Bundle bundle,
                                       int requestCode) {
        Intent intent = new Intent();
        intent.setClass( this, cls );
        if (bundle != null) {
            intent.putExtras( bundle );
        }
        startActivityForResult( intent, requestCode );
    }

    /**
     * 含有Bundle通过Class跳转界面
     **/
    public void startActivity(Class<?> cls, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass( this, cls );
        if (bundle != null) {
            intent.putExtras( bundle );
        }
        startActivity( intent );
    }


    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onPause() {
        super.onPause();

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
//        AppManager.getAppManager().finishActivity(this);
    }

    /**
     * 清除editText的焦点
     *
     * @param v   焦点所在View
     * @param ids 输入框
     */
    public void clearViewFocus(View v, int... ids) {
        if (null != v && null != ids && ids.length > 0) {
            for (int id : ids) {
                if (v.getId() == id) {
                    v.clearFocus();
                    break;
                }
            }
        }
    }

    /**
     * 隐藏键盘
     *
     * @param v   焦点所在View
     * @param ids 输入框
     * @return true代表焦点在edit上
     */
    public boolean isFocusEditText(View v, int... ids) {
        if (v instanceof EditText) {
            EditText tmp_et = (EditText) v;
            for (int id : ids) {
                if (tmp_et.getId() == id) {
                    return true;
                }
            }
        }
        return false;
    }


    //是否触摸在指定view上面,对某个控件过滤
    public boolean isTouchView(View[] views, MotionEvent ev) {
        if (views == null || views.length == 0) return false;
        int[] location = new int[2];
        for (View view : views) {
            view.getLocationOnScreen( location );
            int x = location[0];
            int y = location[1];
            if (ev.getX() > x && ev.getX() < (x + view.getWidth())
                    && ev.getY() > y && ev.getY() < (y + view.getHeight())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
//        if (System.currentTimeMillis() - lastClickTime < FAST_CLICK_DELAY_TIME) {
//            return true;
//        }
//        lastClickTime = System.currentTimeMillis();
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            if (isTouchView( filterViewByIds(), ev )) return super.dispatchTouchEvent( ev );
            if (hideSoftByEditViewIds() == null || hideSoftByEditViewIds().length == 0)
                return super.dispatchTouchEvent( ev );
            View v = getCurrentFocus();
            if (isFocusEditText( v, hideSoftByEditViewIds() )) {
                //隐藏键盘
//                KeyBoardUtils.hideInputForce(this);
                clearViewFocus( v, hideSoftByEditViewIds() );
            }
        }
        return super.dispatchTouchEvent( ev );

    }


    /**
     * 传入EditText的Id
     * 没有传入的EditText不做处理
     *
     * @return id 数组
     */
    public int[] hideSoftByEditViewIds() {
        return null;
    }

    /**
     * 传入要过滤的View
     * 过滤之后点击将不会有隐藏软键盘的操作
     *
     * @return id 数组
     */
    public View[] filterViewByIds() {
        return null;
    }

    protected abstract void initViews();

    protected abstract void initData();

    protected abstract int getLayoutResource();


    public void initState() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = this.getWindow();
            //取消状态栏透明
            window.clearFlags( WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS );
            //添加Flag把状态栏设为可绘制模式
            window.addFlags( WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS );
            //设置状态栏颜色
            window.setStatusBarColor( Color.parseColor( "#ffffff" ) );
            //设置系统状态栏处于可见状态
            getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR );

//            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
            //让view不根据系统窗口来调整自己的布局
            ViewGroup mContentView = (ViewGroup) window.findViewById( Window.ID_ANDROID_CONTENT );
            View mChildView = mContentView.getChildAt( 0 );
            if (mChildView != null) {
                ViewCompat.setFitsSystemWindows( mChildView, false );
                ViewCompat.requestApplyInsets( mChildView );
            }
        }
    }

    /**
     * 展示加载框
     *
     * @param mActivity
     * @time 2020/4/21 11:16
     */
    public void showProgressDialog(Activity mActivity) {
        if (NetworkUtil.isNetworkAvailable( this )) {
            if (mActivity != null) {
                // 这个函数用来设置 Dialog 周围的颜色。系统默认的是半透明的灰色。值设为0则为完全透明。
                this.getWindow().setDimAmount( 3 );
                progressDialog = new ProgressDialog( BaseActivity.this );
                //设置进度条风格，风格为圆形，旋转的
                progressDialog.setProgressStyle(
                        ProgressDialog.STYLE_SPINNER );
                //设置ProgressDialog 标题
//        progressDialog.setTitle("下载");
                //设置ProgressDialog 提示信息
                progressDialog.setMessage( "加载中..." );
                //设置ProgressDialog 标题图标
//        progressDialog.setIcon(android.R.drawable.btn_star);
                //设置ProgressDialog 的进度条是否不明确
                progressDialog.setIndeterminate( false );
                //设置ProgressDialog 是否可以按退回按键取消
                progressDialog.setCancelable( true );
                progressDialog.setProgressStyle( R.style.loading_dialog );
                // 让ProgressDialog显示
                progressDialog.show();
            }

        }

    }

    public void dismissProgressDialog() {
//        mHandler.postDelayed( sRunnable, 1000 );
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }

    @Override
    public Resources getResources() {
        Resources resources = super.getResources();
        return resources;
    }

    public void hintKeyBoard(EditText editText) {
        //拿到InputMethodManager
        InputMethodManager imm = (InputMethodManager) this.getSystemService( Context.INPUT_METHOD_SERVICE );
        imm.hideSoftInputFromWindow( editText.getWindowToken(), 0 );
        //如果window上view获取焦点 && view不为空
//        if (imm.isActive() && getActivity().getCurrentFocus() != null) {
//            //拿到view的token 不为空
//            if (getActivity().getCurrentFocus().getWindowToken() != null) {
//                //表示软键盘窗口总是隐藏，除非开始时以SHOW_FORCED显示。
//                imm.hideSoftInputFromWindow( getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS );
//            }
//        }
    }

}